<?php
/**
 * Created by PhpStorm.
 * User: 57124
 * Date: 2022/2/21
 * Time: 14:32
 */

namespace app\controller;

use app\BaseController;
use app\util\Tools;
use app\validate\User;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

/**
 * Class 注册、登录_API
 * @package app\controller
 */
class Api extends BaseController {
    // 中间件
    //protected $middleware = ['app\middleware\Check'];

    // 注册
    public function register(){
        $name = input("name");
        $password = input("password");
        $mobile = input("mobile");
        $code = input("smsCode");
        if(empty($mobile) || empty($code)){
            return json(["msg"=> "手机号/验证码为空","code"=> 4002]);
        }else{
            $tools = new Tools();
            $user = new \app\model\User();
            $isMobile = preg_match('/^[1][3,4,5,7,8,9][0-9]{9}$/', $mobile, $matches);
            if ($isMobile == 1) {
                $isName = $user::where("mobile",$mobile)->value("mobile");
                if($isName){
                    return json(["msg"=>"该手机号已注册，请去登录","code"=>4001]);
                }
                $cacheCode = Cache::get($mobile);
                if($code != $cacheCode){
                    return json(["msg"=>"验证错误！","code"=> 4004]);
                }
                $date = date("Y-m-d H:i:s");
                $uniqueId = "witshark".$tools ->getRand(3).time();
                $data = [
                    "_id" => $uniqueId,
                    'name'  => $name,
                    "password"=> $tools ->encrypt($password),
                    "mobile"  => $mobile,
                    "updated" => $date,
                    "created" => $date,
                ];
            }else{
                return json(["msg"=>"手机号格式出错了，请填写正确的手机号","code"=>4003]);
            }
            // 注册验证
            try {
                validate(User::class)->check($data); // 属性验证
                Db::name("zs_user")->insert($data);   // 新增
                $tk = $tools -> createToken($name);// 创建 token
                // 记录日志
                $logData = "msg=注册，mobile=".$mobile."，name=".$name."，date=".date("Y-m-d H:i:s")."；\n";
                $logPath = $tools ->createLogFile();
                $logFile = fopen($logPath,"a");
                fwrite($logFile,$logData);
                fclose($logFile);

                return json(["msg"=>"注册成功！", "code"=>200, "token"=>$tk]);
            } catch (ValidateException $e) {
                return json(["msg"=>$e->getError(), "code"=>5001]);
            }
        }
    }
    // 登录
    public function login(){
        if(request()->isPost()){
            $mobile = input('mobile');
            $code = input("smsCode");
            if(empty($mobile) || empty($code)){
                return json(["msg"=> "手机号/验证码为空","code"=> 4002]);
            }else{
                $cacheCode = Cache::get($mobile);
                $user = new \app\model\User();
                //查询用户是否存在
                $users = $user::field("name,mobile")->where("name|mobile",$mobile)->find();
                if(empty($users["mobile"])){
                    return json(["msg"=>"该手机号不存在","code"=> 4003]);
                }else{
                    if($code != $cacheCode){
                        return json(["msg"=>"验证错误！","code"=> 4004]);
                    }else{
                        $tools = new Tools();
                        $tk = $tools -> createToken($users["mobile"]);// 创建 token

                        $user::where("mobile",$mobile)->update(["updated"=>date("Y-m-d H:i:s")]); //更新时间
                        // 记录日志
                        $logData = "msg=验证码登录，mobile=".$mobile."，name=".$users['name']."，date=".date("Y-m-d H:i:s")."；\n";
                        $logPath = $tools ->createLogFile();
                        $logFile = fopen($logPath,"a");
                        fwrite($logFile,$logData);
                        fclose($logFile);

                        return json(["msg"=>"登录成功","code"=>200,"token"=> $tk, "mobile"=>$users["mobile"]]);
                    }
                }
            }
        }
        return json(["msg"=>"请求错误！","code"=> 4001]);
    }
    // 微信登录（有则直接登录，无则注册并登录）
    public function wxLogin(){
        $code = input('code');
        $encryptedData = input('encryptedData');
        $session = $this -> appletSession($code);
        $sessionKey = $session["session_key"];
        if(strlen($sessionKey) != 24){return json(["code"=>-41001]);}
        $aesKey = base64_decode($sessionKey);
        $iv = input('iv');
        if (strlen($iv) != 24) {return json(["code"=>-41002]);}
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result,true);
        if($dataObj  == NULL ) {return json(["code"=>-41003]);}
        $mobile = $dataObj["phoneNumber"];
        return json(["msg"=>'success',"mobile"=>$mobile,"code"=>200]);
        if($mobile){
            $user = new \app\model\User();
            $tools = new Tools();
            $uniqueId = "witshark".$tools ->getRand(3).time();
            $data = [
                "_id" => $uniqueId,
                'nickname'  => "微信用户",
                "mobile"  => $mobile,
                "updated" => date("Y-m-d H:i:s"),
            ];
            $user -> save($data);

            // 记录日志
            $logData = "msg=微信登录，mobile=".$mobile."，name=微信用户，date=".date("Y-m-d H:i:s")."；\n";
            $logPath = $tools ->createLogFile();
            $logFile = fopen($logPath,"a");
            fwrite($logFile,$logData);
            fclose($logFile);

            return json(["msg"=>'success',"mobile"=>$mobile,"code"=>200]);
        }
        return json(["msg"=>"请求错误！","code"=> 4001]);
    }

    // 短信_验证码 (注册)
    public function smsCodeRe(){
        try{
            $mobile = input('mobile');
            $cache = Cache::get($mobile);
            $user = new \app\model\User();
            if($cache){
                return json(['msg'=>'验证码请求过于频繁，请稍后再试！','code'=>200,"vCode"=>$cache]);
            }else{
                $ph = $user::where('mobile',$mobile)->value("mobile");
                $code = mt_rand(100000,999999);
                if(empty($ph) && !empty($code)){
                    Cache::set($mobile,$code,900);//缓存验证码15分钟
                    //return json(['msg'=>'短信验证码','status'=>'success','code'=>$sCode]);
                    $appid = SMS_ID;
                    $appkey = SMS_SECRET;
                    $templateId = 493640;
                    $smsSign = "xxx科技";
                    //指定模板单发短信
                    try {
//                    $ssender = new SmsSingleSender($appid, $appkey);
//                    $params = [$scode];      //参数列表 验证码
//                    $result = $ssender->sendWithParam("86", $mobile, $templateId,$params, $smsSign, "", "");
//                    $rsp = json_decode($result,true);
                        //return json(['msg'=>'验证码已发送，请注意查收！','code'=>200]);
                        return json(['msg'=>'验证码已发送，请注意查收！','code'=>200,"vCode"=>$code]);
                    } catch(\Exception $e) {
                        //echo var_dump($e);
                        return json(['msg'=>'验证码发送失败，请联系管理员！','code'=>402,"vCode"=>""]);
                    }
                }
                return json(['msg'=>'该手机号已注册','code'=>401,"vCode"=>""]);
            }
        }catch (Exception $e){
            return json(['msg'=>'出错了！','code'=>400,"vCode"=>""]);
        }
    }
    // 短信_验证码 (登录)
    public function smsCode(){
        try{
            $mobile = input('mobile');
            $cache = Cache::get($mobile);
            $user = new \app\model\User();
            if($cache){
                return json(['msg'=>'验证码请求过于频繁，请稍后再试！','code'=>200,"vCode"=>$cache]);
            }else{
                $ph = $user::where('name|mobile',$mobile)->value("mobile");
                $code = mt_rand(100000,999999);
                if(!empty($ph) && !empty($code)){
                    Cache::set($mobile,$code,900);//缓存验证码15分钟
                    //return json(['msg'=>'短信验证码','status'=>'success','code'=>$sCode]);
                    $appid = SMS_ID;
                    $appkey = SMS_SECRET;
                    $templateId = 493640;
                    $smsSign = "xxx科技";
                    //指定模板单发短信
                    try {
//                    $ssender = new SmsSingleSender($appid, $appkey);
//                    $params = [$scode];      //参数列表 验证码
//                    $result = $ssender->sendWithParam("86", $mobile, $templateId,$params, $smsSign, "", "");
//                    $rsp = json_decode($result,true);
                        //return json(['msg'=>'验证码已发送，请注意查收！','code'=>200]);
                        return json(['msg'=>'验证码已发送，请注意查收！','code'=>200,"vCode"=>$code]);
                    } catch(\Exception $e) {
                        //echo var_dump($e);
                        return json(['msg'=>'验证码发送失败，请联系管理员！','code'=>402,"vCode"=>""]);
                    }
                }
                return json(['msg'=>'手机号不可为空','code'=>401,"vCode"=>""]);
            }
        }catch (Exception $e){
            return json(['msg'=>'出错了！','code'=>400,"vCode"=>""]);
        }
    }

    //
    public function wxLogin2(){
        if(request()->isPost()){
            $token = $this ->wxAppletToken();
            $code = input('code');
            $tools = new Tools();
            $path = APPLET_APP_URL.'/wxa/business/getuserphonenumber';
            $arr = array(
                'access_token' => $token,
                'code' => $code,
            );
            $res = $tools -> curl_post($path,$arr);
            return json(["res"=>$res,"code"=>$code,'token'=>$token]);
        }
        return json(["msg"=>"请求错误！","code"=> 4001]);
    }


    // 测试 API
    public function test(){
        return "什么鬼呀";
    }
    /** 获取微信手机号 */
    // 封装的请求路径
    protected function appletSession($code){
        $tools = new Tools();
        $path = APPLET_APP_URL.'/sns/jscode2session';
        $arr = array(
            'appid'      => APPLET_APP_ID,
            'secret'     => APPLET_APP_SECRET,
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        );
        $url = $tools -> joinParams($path,$arr);
        $res = $tools -> curl_get($url);
        $res = json_decode($res,true);
        return $res;
    }

    // 微信小程序 access_token
    public function wxAppletToken(){
        $tools = new Tools();
        $path = APPLET_APP_URL.'/cgi-bin/token';
        $arr = array(
            'appid'      => APPLET_APP_ID,
            'secret'     => APPLET_APP_SECRET,
            'grant_type' => 'client_credential'
        );
        $url = $tools -> joinParams($path,$arr);
        $res = $tools -> curl_get($url);
        $res = json_decode($res,true);
        return $res["access_token"];
    }
}